﻿using System;
using System.Collections.Generic;

namespace ObserverPattern.SimpleImplement;

// 订阅号抽象类
public abstract class Media(string symbol, string info)
{
    // 保存订阅者列表
    private readonly List<IObserver> _observers = [];

    public string Symbol { get; } = symbol;
    public string Info { get; } = info;

    #region 新增对订阅号列表的维护操作

    public void AddObserver(IObserver ob)
    {
        _observers.Add(ob);
    }

    public void RemoveObserver(IObserver ob)
    {
        _observers.Remove(ob);
    }

    #endregion

    public void Update()
    {
        // 遍历订阅者列表进行通知
        foreach (var ob in _observers)
        {
            ob.ReceiveAction(this);
        }
    }
}

// 具体订阅号类
public class TencentGame(string symbol, string info) : Media(symbol, info);

// 订阅者接口
public interface IObserver
{
    void ReceiveAction(Media media);
}

// 具体的订阅者类
public class Subscriber(string name) : IObserver
{
    private string Name { get; } = name;

    public void ReceiveAction(Media media)
    {
        Console.WriteLine("\"{0}\"收到来自\"{1}\"的通知\"{2}\"", Name, media.Symbol, media.Info);
    }
}